package com.itheima.advice;

import com.itheima.service.LogService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class TransfarAdvice {
    //注入
    @Autowired
    public LogService logService;

    //切点
    @Pointcut("execution(* com.itheima.service.AccountService.transfer(..))")
    public void pt(){}

   @Around("pt()")
    public Object around(ProceedingJoinPoint pjp){
        //1. 获取参数
        Object[] args = pjp.getArgs();
        String out = args[0].toString();
        String in = args[1].toString();
        double money = Double.parseDouble(args[2].toString());
        Object proceed = null;
        try {
            //2.执行业务
            proceed = pjp.proceed();
            //3.1返回通知的记录 - 成功（！！！注入logService）
            String info = "转账成功！";
            System.out.println(info);
            logService.log(out,in,money,info);
        } catch (Throwable e) {
            //3.2异常通知 - 失败原因
            String info2 = "转账失败" + e.getMessage();
            System.out.println(info2);
            logService.log(out,in,money,info2);

            //环绕通知已经把异常处理掉了，所以不会回滚。要手动抛出异常

            throw  new RuntimeException(info2);
        }
        //4.后置通知- 业务完成
        System.out.println("转账操作完成！");
        return null;
    }

   /* //1.返回通知
    @AfterReturning(value = "pt()" , returning = "obj")
    public void returning(JoinPoint point , Object obj){
        //1.获取参数
        Object[] args = point.getArgs();
        String out = args[0].toString();
        String in = args[1].toString();
        double money = Double.parseDouble(args[2].toString());

        //3.1返回通知的记录 - 成功（！！！注入logService）
        String info = "转账成功！";
        System.out.println(info);
        logService.log(out,in,money,info);
    }

    //2.异常通知
    @AfterThrowing(value = "pt()" , throwing = "t")
    public void throwing(JoinPoint point,Throwable t){
        //1. 获取参数
        Object[] args = point.getArgs();
        String out = args[0].toString();
        String in = args[1].toString();
        double money = Double.parseDouble(args[2].toString());

        //3.2异常通知 - 失败原因
        String info2 = "转账失败" + t.getMessage();
        System.out.println(info2);
        logService.log(out,in,money,info2);
    }*/
}
